<?php

namespace App\Orchid\Screens\Category;

use App\Models\Category;
use Illuminate\Http\Request;
use Orchid\Screen\Screen;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Fields\TextArea;
use Orchid\Screen\Fields\Relation;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;
use Orchid\Support\Facades\Layout;
use Illuminate\Support\Str;

class CategoryEditScreen extends Screen
{
    /**
     * @var Category
     */
    public $category;

    /**
     * Fetch data to be displayed on the screen.
     *
     * @param Category $category
     *
     * @return array
     */
    public function query(Category $category): iterable
    {
        return [
            'category' => $category,
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return $this->category->exists ? '编辑分类' : '新建分类';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return $this->category->exists ? '编辑现有分类信息' : '创建新的文章分类';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Button::make('保存')
                ->icon('check')
                ->method('save'),

            Button::make('删除')
                ->icon('trash')
                ->method('remove')
                ->canSee($this->category->exists)
                ->confirm('确定要删除这个分类吗？'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::rows([
                Input::make('category.name')
                    ->title('分类名称')
                    ->placeholder('输入分类名称')
                    ->required()
                    ->help('分类的显示名称'),

                Input::make('category.slug')
                    ->title('Slug')
                    ->placeholder('自动生成或手动输入')
                    ->help('URL友好的标识符，留空将自动生成'),

                Relation::make('category.parent_id')
                    ->title('父分类')
                    ->fromModel(Category::class, 'name')
                    ->empty('无父分类（顶级分类）')
                    ->help('选择父分类创建层级结构'),

                TextArea::make('category.description')
                    ->title('描述')
                    ->placeholder('输入分类描述')
                    ->rows(4)
                    ->help('分类的详细描述信息'),
            ]),
        ];
    }

    /**
     * Save category
     *
     * @param Request $request
     * @param Category $category
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Category $category)
    {
        $request->validate([
            'category.name' => 'required|string|max:255',
            'category.slug' => 'nullable|string|max:255|unique:categories,slug,' . $category->id,
            'category.parent_id' => 'nullable|exists:categories,id',
            'category.description' => 'nullable|string',
        ]);

        $data = $request->get('category');
        
        // 自动生成slug
        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }
        
        // 确保slug唯一
        $data['slug'] = $this->ensureUniqueSlug($data['slug'], $category->id);
        
        // 防止设置自己为父分类
        if ($category->exists && $data['parent_id'] == $category->id) {
            Toast::error('不能将分类设置为自己的父分类');
            return back();
        }
        
        // 防止循环引用
        if ($category->exists && $data['parent_id']) {
            $parent = Category::find($data['parent_id']);
            if ($parent && $this->wouldCreateCycle($category, $parent)) {
                Toast::error('不能创建循环引用的分类层级');
                return back();
            }
        }

        $category->fill($data)->save();

        Toast::info('分类已保存');

        return redirect()->route('platform.categories');
    }

    /**
     * Remove category
     *
     * @param Category $category
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Category $category)
    {
        // 检查是否有子分类
        if ($category->children()->count() > 0) {
            Toast::error('无法删除包含子分类的分类');
            return back();
        }
        
        // 检查是否有关联的文章
        if ($category->posts()->count() > 0) {
            Toast::error('无法删除包含文章的分类');
            return back();
        }
        
        $category->delete();

        Toast::info('分类已删除');

        return redirect()->route('platform.categories');
    }
    
    /**
     * Ensure slug is unique
     *
     * @param string $slug
     * @param int|null $excludeId
     * @return string
     */
    private function ensureUniqueSlug(string $slug, ?int $excludeId = null): string
    {
        $originalSlug = $slug;
        $counter = 1;
        
        while (Category::where('slug', $slug)
            ->when($excludeId, fn($query) => $query->where('id', '!=', $excludeId))
            ->exists()) {
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
    
    /**
     * Check if setting parent would create a cycle
     *
     * @param Category $category
     * @param Category $parent
     * @return bool
     */
    private function wouldCreateCycle(Category $category, Category $parent): bool
    {
        $current = $parent;
        while ($current) {
            if ($current->id === $category->id) {
                return true;
            }
            $current = $current->parent;
        }
        return false;
    }
}